/**
 * User: annson
 **/
ns = {
    ok: function (msg, fn) {
        return layer.msg(msg, {icon: 1, time: 2000, shade: [0.2, '#000']}, fn);
    },

    error: function (msg) {
    	if(!msg){
            return layer.alert("操作失败，请重试！", {icon: 2});
        }
        return layer.alert(msg, {icon: 2});
        //return layer.msg(msg, {icon: 5, time: 3000, shade: [0.2, '#000']});
    },
    errorTip: function (msg) {
        return layer.msg(msg, {icon: 5, time: 3000, shade: [0.2, '#000']});
    },


    load: function (msg, fn) {
        if(!msg){
            return layer.load(1, {shade: [0.1, '#000']});
        }

        return layer.msg(msg, {
            icon: 16,
            shade: [0.1, '#000'],
            time: 0//2秒关闭（如果不配置，默认是3秒）
        }, fn);
    }

    ,close : function(index){
        layer.close(index);
    }

    ,closeAll : function(){
        layer.closeAll();
    }
    ,confirm : function(content, yes, cancel){
    	
    	return layer.confirm(content, {icon: 3, title:'提示', btn: ['确认', '取消']
        }, yes, cancel);
    }
};



function toPage(page, limit) {

    var $searchForm = $("#" + searchFormID);
    if(page) {
        $searchForm.find("input[name=currentPage]").val(page);
    }

    if(limit) {
         $searchForm.find("input[name=limit]").val(limit);
    }
    var loadIndex = ns.load("数据加载中...");


    $.ajax({
        type: "POST",
        url: pageListUrl,
        dataType: "json",
        data: $searchForm.serialize(),
       /* data: {
            currentPage: page,
            toolStyle : toolStyle,
            limit: limit
        },*/
        async: true,
        success: function (data) {
            ns.close(loadIndex);
            if (data.success) {
                var html = template(detailTbodyTemplateID, data.data);

                $("#" + detailTbodyID).html(html);
                $("#" + pageToolID).html(data.data.pageToolHtml);
            } else {
                ns.error(data.message);
            }

        },
        error: function () {
            ns.close(loadIndex);
            ns.error('数据加载失败！');
        }
    });
}


function add(successRunFunction, isRefresh){
    openEditWin("新增", {}, successRunFunction, isRefresh);
}

function edit(id, successRunFunction, isRefresh) {
    //Ajax获取
    var loadIndex = ns.load();
    $.ajax({
        type: "POST",
        url: loadByIdUrl + id,
        dataType: "json",
        success: function (data) {
            ns.close(loadIndex);
            if (data.success) {
                ns.close(loadIndex);

                openEditWin("编辑", data.data, successRunFunction, isRefresh);
            } else {
                ns.error('数据加载失败' + data.message);
            }
        },
        error: function () {
            ns.close(loadIndex);
            ns.error('提交失败！');
        }
    });
}


function openEditWin(title, data, successRunFunction, isRefresh) {

    var contentHtml = template(editTemplateID, data);

    if(isRefresh === undefined){
        isRefresh = true;
    }

    layer.open({
        type: 1,
        title: title,
        area: '600px',
        btn: ['保 存', '取 消'],
        content: contentHtml,
        yes: function (index, layero) {
            var layerIndex = ns.load();
            $.ajax({
                type: "POST",
                url: saveUrl,
                dataType: "json",
                data: $("#" + editFormID).serialize(),
                success: function (data) {
                    ns.close(layerIndex);
                    if (data.success) {
                        ns.ok('操作成功!', function () {
                            ns.closeAll();
                            if(isRefresh) {
                                toPage(1);
                            }
                        });
                        if(successRunFunction){
                            successRunFunction();
                        }
                    } else {
                        ns.error('提交失败' + data.message);
                    }
                },
                error: function () {
                    ns.close(layerIndex);
                    ns.error('提交失败！');
                }
            });
        }, cancel: function (index) {
            ns.closeAll();
        }
    });

    $("input[type=checkbox]").change(function(){
       $(this).prev().val($(this).prop("checked"));
    });
}


function del(id) {
    var layerIndex = layer.confirm('数据删除后将不可恢复，确定删除？', {
        icon: 3,
        title:'提示',
        btn: ['确认', '取消']
    }, function () {
        ns.close(layerIndex);
        layerIndex = ns.load("正在保存数据.....");
        $.ajax({
            type: 'POST',
            url: delByIdUrl + id,
            cache: false,
            data: {
                id: id
            },
            error: function () {
                ns.error('操作失败');
            },
            success: function (data) {
                ns.close(layerIndex);
                if (data.success) {
                    ns.ok('操作成功', function () {
                        toPage(1);
                    });
                } else {
                    ns.error('操作失败：' + data.message);
                }
            }
        });
    });
}


function enable(id) {
    layer.confirm('确定操作？', function () {
        $.ajax({
            type: "POST",
            url: enableByIdUrl + id,
            dataType: "json",
            async: true,
            error: function () {
                ns.error('操作失败');
            },
            success: function (data) {
                if (data.success) {
                     ns.ok('操作成功', function () {
                        toPage();
                    });
                } else {
                    ns.error('操作失败：' + data.message);
                }
            }
        });
    });
}

function disable(id) {
    layer.confirm('确定操作？', function () {
        $.ajax({
            type: "POST",
            url: disableByIdUrl + id,
            dataType: "json",
            async: true,
            error: function () {
                ns.error('操作失败');
            },
            success: function (data) {
                if (data.success) {
                     ns.ok('操作成功', function () {
                        toPage();
                    });
                } else {
                    ns.error('操作失败：' + data.message);
                }

            }
        });
    });
}


function selectAll(obj, name){
    $("input[name='" + name + "']").prop("checked", $(obj).prop("checked"));
}

(function($){
    $.fn.serializeJson=function(){
        var serializeObj={};
        var array=this.serializeArray();
        var str=this.serialize();
        $(array).each(function(){
            if(serializeObj[this.name]){
                if($.isArray(serializeObj[this.name])){
                    serializeObj[this.name].push(this.value);
                }else{
                    serializeObj[this.name]=[serializeObj[this.name],this.value];
                }
            }else{
                serializeObj[this.name]=this.value;
            }
        });
        return serializeObj;
    };
})(jQuery);